package com.dminvoicemanager.itinerary;

import com.dminvoicemanager.DM_Cash_Cheque_Receipt;
import com.dminvoicemanager.DM_InvoiceMenu;
import com.dminvoicemanager.DM_InvoiceNew;
import com.dminvoicemanager.DM_Stock_UnLoading;
import com.dminvoicemanager.R;
import com.dminvoicemanager.itinerary.DM_Itinerary_Calendar_Adapter;
import com.dminvoicemanager.itinerary.DM_GabrielblGridView;
import com.dminvoicemanager.printdoc.DM_Print_Main_Invoice;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class DM_Itinerary_Report_Main extends Activity {
	public GregorianCalendar month, itemmonth;// calendar instances.

	public DM_Itinerary_Calendar_Adapter adapter;// adapter instance
	public Handler handler;// for grabbing some event values for showing the dot
							// marker.
	public ArrayList<String> items; // container to store calendar items which
									// needs showing the event marker
	private SQLiteDatabase mydb;
	private String DBNAME = "dminvoicemanager.db";
	// Master Tables
	private String USER_SETTINGS = "usersettings";
	private String ITEM_COMPANY_SETTING = "fCompanySetting";
	private String ITEM_CONTROL = "fControl";
	private String INV_COMPANY_BRANCH = "FCompanyBranch";

	// Itinerary Report
	private String ITINERARY_HEAD = "FItenrHed";
	private String ITINERARY_DETAILS = "FItenrDet";
	private String ITINERARY_DETTAIL_DET = "FIteDetDet";

	AlertDialog InvoiceHeaderAlert = null;
	final private static int DIALOG_CANCEL_INVOICE = 1;
	final private static int DIALOG_UNDO_INVOICE = 2;
	final private static int DIALOG_PRINT_INVOICE = 3;
	final private static int DIALOG_SAVE_INVOICE = 4;
	final private static int DIALOG_SELECT_CUSTOMER = 5;

	private static final String TAG = null;

	Button etdmitineraryrefval,account_saveButton;
	EditText etdmitineraryremarkval, etdmitirouteval, etdmitioutletval,
			etdmitirdtargetval;
	String selectedTxnDate, currentUserStLoad, currentUserPrefixLoad,
			currentUserLocation, stlAgentPrefixType, stlAgentDealCode,
			StlTransTypePrefix, TagId, tempRepItinerarySerialStr,
			RepStItinararyCode, saveTempItineraryCode, deviceUser,
			selectedCalYear, selectedCalMonth, selectedCalDate, month_name,
			ItiCurrentRefNo, IDENTIFIRE, matchIdentifire;

	public void ExitFromForm(View view) {
		Intent myIntent = new Intent(view.getContext(), DM_InvoiceMenu.class);
		myIntent.putExtra("TAGID", "SALES");
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivityForResult(myIntent, 0);
		InvoiceHeaderAlert.dismiss();
		finish();

	}

	public void btnSaveInvoice(View view) {
		try {
			showDialog(DIALOG_SAVE_INVOICE);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public void btnPrintInvoice(View view) {
		try {
			showDialog(DIALOG_PRINT_INVOICE);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	// ==============Undo Invoice====================
	public void btnUndoInvoice(View view) {

		if (etdmitineraryrefval.length() != 0) {
			try {
				showDialog(DIALOG_UNDO_INVOICE);
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		} else {
			try {
				showDialog(DIALOG_UNDO_INVOICE);
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}

	}

	// Undo Invoice Handling
	public void btnUndoInvoiceCancel(View view) {
		// synchdata();
		InvoiceHeaderAlert.dismiss();
	}

	public void btnUndoInvoiceAccept(View view) {
		Intent myIntent = new Intent(view.getContext(), DM_InvoiceMenu.class);
		myIntent.putExtra("TAGID", "SALES");
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivityForResult(myIntent, 0);
		InvoiceHeaderAlert.dismiss();
		finish();
	}

	public void btnUndoInvoiceAcceptExit(View view) {
		Intent myIntent = new Intent(view.getContext(), DM_InvoiceMenu.class);
		myIntent.putExtra("TAGID", "SALES");
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivityForResult(myIntent, 0);
		InvoiceHeaderAlert.dismiss();
		finish();
	}

	// ==============Cancel Invoice====================
	public void btnCancelInvoice(View view) {
		try {
			showDialog(DIALOG_CANCEL_INVOICE);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	// Undo Invoice Handling
	public void btnCancelInvoiceReject(View view) {
		// synchdata();
		InvoiceHeaderAlert.dismiss();
	}

	public void btnCancelInvoiceAccept(View view) {
		Intent myIntent = new Intent(view.getContext(), DM_InvoiceMenu.class);
		myIntent.putExtra("TAGID", "SALES");
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivityForResult(myIntent, 0);
		finish();
	}

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dm_itinerary_report_main);
		Bundle bundle = getIntent().getExtras();
		TagId = bundle.getString("TAGID");

		TextView txtHeading = (TextView) findViewById(R.id.txtHeading);
		txtHeading.setText("Itinerary Entry");

		etdmitineraryrefval = (Button) findViewById(R.id.etdmitineraryrefval);
		account_saveButton = (Button) findViewById(R.id.account_saveButton);
		etdmitineraryremarkval = (EditText) findViewById(R.id.etdmitineraryremarkval);
		etdmitirouteval = (EditText) findViewById(R.id.etdmitirouteval);
		etdmitioutletval = (EditText) findViewById(R.id.etdmitioutletval);
		etdmitirdtargetval = (EditText) findViewById(R.id.etdmitirdtargetval);
		account_saveButton.setEnabled(true);
		// Main Itinerary Report functions
		currentUserStLoadChk();// Check Current User
		stLoadingAgentPrefix();// Check Current Agent Prefix
		stLoadingTransType();// Check Current Trans Type
		getCurrentTimeString();// To get current date/month/year
		getCurrentMonthName(); // To get current month name
		deviceName();// get device name
		getCurrentTimeIdentifire();
		checkLatestItinerarySerial();

		// ********Calender View ************
		Locale.setDefault(Locale.US);

		month = (GregorianCalendar) GregorianCalendar.getInstance();
		itemmonth = (GregorianCalendar) month.clone();

		items = new ArrayList<String>();
		adapter = new DM_Itinerary_Calendar_Adapter(this, month);

		GridView gridview = (GridView) findViewById(R.id.gridview);
		gridview.setAdapter(adapter);

		handler = new Handler();
		handler.post(calendarUpdater);

		TextView title = (TextView) findViewById(R.id.title);
		title.setText(android.text.format.DateFormat.format("MMMM yyyy", month));

		RelativeLayout previous = (RelativeLayout) findViewById(R.id.previous);

		previous.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				setPreviousMonth();
				refreshCalendar();
			}
		});

		RelativeLayout next = (RelativeLayout) findViewById(R.id.next);
		next.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				setNextMonth();
				refreshCalendar();

			}
		});
		// ************Calender Grid Item Click Event************
		gridview.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View v,
					int position, long id) {

				((DM_Itinerary_Calendar_Adapter) parent.getAdapter())
						.setSelected(v);
				String selectedGridDate = DM_Itinerary_Calendar_Adapter.dayString
						.get(position);
				String[] separatedTime = selectedGridDate.split("-");
				String gridvalueString = separatedTime[2].replaceFirst("^0*",
						"");// taking last part of date. ie; 2 from 2012-12-02.

				// Recreate TxnDate
				selectedCalYear = separatedTime[0]; // year
				selectedCalMonth = separatedTime[1]; // month
				selectedCalDate = separatedTime[2]; // date
				selectedTxnDate = selectedCalDate + "/" + selectedCalMonth
						+ "/" + selectedCalYear;

				int gridvalue = Integer.parseInt(gridvalueString);
				// navigate to next or previous month on clicking offdays.
				if ((gridvalue > 10) && (position < 8)) {
					setPreviousMonth();
					refreshCalendar();
				} else if ((gridvalue < 7) && (position > 28)) {
					setNextMonth();
					refreshCalendar();
				}
				((DM_Itinerary_Calendar_Adapter) parent.getAdapter())
						.setSelected(v);

				showToast(selectedGridDate);

			}
		});
		// ************End Calender Grid Item Click Event************

		// ************Calender Grid Item Long Click Event************
		gridview.setLongClickable(true);
		gridview.setOnItemLongClickListener(new OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View v,
					int position, long id) {

				((DM_Itinerary_Calendar_Adapter) parent.getAdapter())
						.setSelected(v);
				String selectedGridDate = DM_Itinerary_Calendar_Adapter.dayString
						.get(position);
				String[] separatedTime = selectedGridDate.split("-");
				// Recreate TxnDate
				selectedCalYear = separatedTime[0]; // year
				selectedCalMonth = separatedTime[1]; // month
				selectedCalDate = separatedTime[2]; // date

				selectedTxnDate = selectedCalDate + "/" + selectedCalMonth
						+ "/" + selectedCalYear;
				Log.v(TAG, "selectedTxnDate :" + selectedTxnDate);
				matchIdentifire = selectedCalMonth + "" + selectedCalYear;
				navItinararyDetails();
				return true;

			}
		});

		// ********End Calender View ************
	}

	protected void navItinararyDetails() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		try {
			ContentValues newrecItiDet = new ContentValues();
			newrecItiDet.put("Remarks1", etdmitineraryremarkval.getText()
					.toString());
			mydb.update(ITINERARY_HEAD, newrecItiDet, "RefNo ='"
					+ ItiCurrentRefNo.trim() + "'", null);
		} catch (Exception e) {
		}
		Intent myIntent = new Intent(this.getBaseContext(),
				DM_Itinerary_Report_Details.class);
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		myIntent.putExtra("TAGID", matchIdentifire + "=" + selectedTxnDate);
		startActivityForResult(myIntent, 0);
		finish();
		return;
	}

	// *********Check Clicked identifire with Previous identifires
	/*
	 * protected void checkItiRefAvailability() { // TODO Auto-generated method
	 * stub mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
	 * Cursor chkItiAvailability = null; try { chkItiAvailability =
	 * mydb.query(USER_SETTINGS, null, null, null, null, null, null); } catch
	 * (Exception e) { } }
	 */

	// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	// Check Current User
	private void currentUserStLoadChk() {
		// TODO Auto-generated method stub

		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectCurrentuserLoad = null;
		try {
			selectCurrentuserLoad = mydb.query(USER_SETTINGS, null, null, null,
					null, null, null);
		} catch (Exception e) {
		}
		if (selectCurrentuserLoad != null) {
			if (selectCurrentuserLoad.getCount() > 0) {
				while (selectCurrentuserLoad.moveToNext()) {
					currentUserStLoad = selectCurrentuserLoad.getString(1);
					currentUserPrefixLoad = selectCurrentuserLoad.getString(2);
					currentUserLocation = selectCurrentuserLoad.getString(3);
				}
			}
		}
		selectCurrentuserLoad.close();
		mydb.close();
	}

	// Check Current Agent Prefix
	private void stLoadingAgentPrefix() {
		// TODO Auto-generated method stub

		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectAgentPreType = null;

		try {
			selectAgentPreType = mydb.query(ITEM_CONTROL, null, null, null,
					null, null, null);
		} catch (Exception e) {
		}
		if (selectAgentPreType != null) {
			if (selectAgentPreType.getCount() > 0) {
				while (selectAgentPreType.moveToNext()) {
					stlAgentPrefixType = selectAgentPreType.getString(18);
					stlAgentDealCode = selectAgentPreType.getString(19);
				}

			}
		}
		selectAgentPreType.close();
		mydb.close();
	}

	// Check Current Trans Type
	private void stLoadingTransType() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectTransType = null;

		try {
			selectTransType = mydb.query(ITEM_COMPANY_SETTING, null, null,
					null, null, null, null);
		} catch (Exception e) {
		}
		if (selectTransType != null) {
			if (selectTransType.getCount() > 0) {
				while (selectTransType.moveToNext()) {
					String cSettingsCode = selectTransType.getString(1);
					String cCharValue = selectTransType.getString(4);
					if (cSettingsCode.equals("ITNARY")) {
						StlTransTypePrefix = cCharValue.trim();
					}
				}
			}
		}
		selectTransType.close();
		mydb.close();
	}

	private void checkLatestItinerarySerial() {
		// TODO Auto-generated method stub

		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectItinerarySerial = null;

		try {
			selectItinerarySerial = mydb.query(INV_COMPANY_BRANCH, null,
					"cSettingsCode='ITNARY'", null, null, null, null);
		} catch (Exception e) {
		}

		Cursor selectLastItirec = null;
		try {
			selectLastItirec = mydb.query(ITINERARY_HEAD, null, "ItinaryUser='"
					+ currentUserStLoad + "' AND ItenrHedActive='9'", null,
					null, null, null);
		} catch (Exception e) {
		}

		if (selectItinerarySerial != null) {
			if (selectItinerarySerial.getCount() > 0) {
				while (selectItinerarySerial.moveToNext()) {
					String cSettingsCode = selectItinerarySerial.getString(3);
					String nNumVal = selectItinerarySerial.getString(4);
					tempRepItinerarySerialStr = nNumVal.trim();
					if (selectLastItirec != null) {
						if (selectLastItirec.getCount() > 0) {
							if (selectLastItirec.moveToLast()) {
								viewCurrentStockLoad();
							}
						} else if (selectLastItirec.getCount() <= 0) {
							saveItineraryTransaction();// Save Store Loading
						}
					}

				}
			} else {
				tempRepItinerarySerialStr = "1";
				try {
					ContentValues newItinerary = new ContentValues();
					newItinerary.put("BranchCode", currentUserStLoad);
					newItinerary.put("RecordId", "1");
					newItinerary.put("cSettingsCode", "ITNARY");
					newItinerary.put("nNumVal", tempRepItinerarySerialStr);
					mydb.insert(INV_COMPANY_BRANCH, null, newItinerary);
					saveItineraryTransaction();// Save Store Loading

				} catch (Exception e) {
					Toast.makeText(this, e.toString(), Toast.LENGTH_LONG)
							.show();
				}
				mydb.close();
			}
		}
		selectItinerarySerial.close();
		mydb.close();
	}

	// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	private void saveItineraryTransaction() {
		// TODO Auto-generated method stub
		RepStItinararyCode = StlTransTypePrefix.trim()
				+ stlAgentPrefixType.trim() + currentUserPrefixLoad;

		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		try {
			ContentValues saveItinararySummary = new ContentValues();
			try {
				if (tempRepItinerarySerialStr.length() == 1) {
					String newInvNumberStr = "00000"
							+ tempRepItinerarySerialStr;
					saveTempItineraryCode = RepStItinararyCode.trim() + "/"
							+ newInvNumberStr;
				} else if (tempRepItinerarySerialStr.length() == 2) {
					String newInvNumberStr = "0000" + tempRepItinerarySerialStr;
					saveTempItineraryCode = RepStItinararyCode.trim() + "/"
							+ newInvNumberStr;
				} else if (tempRepItinerarySerialStr.length() == 3) {
					String newInvNumberStr = "000" + tempRepItinerarySerialStr;
					saveTempItineraryCode = RepStItinararyCode.trim() + "/"
							+ newInvNumberStr;
				} else if (tempRepItinerarySerialStr.length() == 4) {
					String newInvNumberStr = "00" + tempRepItinerarySerialStr;
					saveTempItineraryCode = RepStItinararyCode.trim() + "/"
							+ newInvNumberStr;
				} else if (tempRepItinerarySerialStr.length() == 5) {
					String newInvNumberStr = "0" + tempRepItinerarySerialStr;
					saveTempItineraryCode = RepStItinararyCode.trim() + "/"
							+ newInvNumberStr;
				} else {
					String newInvNumberStr = tempRepItinerarySerialStr;
					saveTempItineraryCode = RepStItinararyCode.trim() + "/"
							+ newInvNumberStr;
				}
			} catch (Exception e) {

			}

			saveItinararySummary.put("RefNo", saveTempItineraryCode);
			saveItinararySummary.put("DealCode", stlAgentDealCode);
			saveItinararySummary.put("RepCode", currentUserStLoad);
			saveItinararySummary.put("Year", selectedCalYear);
			saveItinararySummary.put("Month", selectedCalMonth);
			saveItinararySummary.put("Remarks1", "");
			saveItinararySummary.put("CostCode", "000");
			saveItinararySummary.put("AddUser", currentUserStLoad);
			saveItinararySummary.put("AddDate", getCurrentTimeString()
					.toString());
			saveItinararySummary.put("AddMach", deviceUser);
			saveItinararySummary.put("TranBatch", "");
			saveItinararySummary.put("TxnDate", getCurrentTimeString()
					.toString());
			saveItinararySummary.put("ItenrHedComplete", "0");
			saveItinararySummary.put("ItenrHedActive", "9");
			saveItinararySummary.put("ItinaryUser", currentUserStLoad);
			saveItinararySummary.put("ItenrHedActiveSerial",
					tempRepItinerarySerialStr);
			saveItinararySummary.put("MonthName", month_name);
			saveItinararySummary.put("currentViewIti", "1");
			saveItinararySummary.put("ItiRefIdentifire",
					getCurrentTimeIdentifire().toString());

			mydb.insert(ITINERARY_HEAD, null, saveItinararySummary);

		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), "Record Not Insert..",
					Toast.LENGTH_SHORT).show();
		}
		mydb.close();
		viewCurrentStockLoad();
	}

	private void viewCurrentStockLoad() {
		// TODO Auto-generated method stub

		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		// String[] resultserial = { "tempRepInvSerial" };
		Cursor selectCurrentStockLoad = null;
		try {
			selectCurrentStockLoad = mydb.query(ITINERARY_HEAD, null,
					"ItinaryUser='" + currentUserStLoad
							+ "' AND ItenrHedActive='9'", null, null, null,
					null);
		} catch (Exception e) {
		}
		if (selectCurrentStockLoad != null) {
			if (selectCurrentStockLoad.getCount() > 0) {
				if (selectCurrentStockLoad.moveToLast()) {
					ItiCurrentRefNo = selectCurrentStockLoad.getString(1);
					String ItiYear = selectCurrentStockLoad.getString(4);
					String ItiMonth = selectCurrentStockLoad.getString(5);
					String ItiRemarks1 = selectCurrentStockLoad.getString(6);

					etdmitineraryrefval.setText(ItiCurrentRefNo);
					etdmitineraryremarkval.setText(ItiRemarks1);
				}
			}
		}

		Cursor selectCurrentStockLoadSum = null;
		try {
			String query = "SELECT D.RouteCode,D.RouteName,D.NoOutlet,D.NoShcuCal,D.RDTarget,D.ActiveRecIdentifire,H.Remarks1,H.ItiRefIdentifire FROM FItenrDet D,FItenrHed H Where D.ActiveRecIdentifire = H.ItiRefIdentifire AND D.RefNo = '"
					+ ItiCurrentRefNo + "'";
			selectCurrentStockLoadSum = mydb.rawQuery(query, null);
		} catch (Exception e) {
		}
		if (selectCurrentStockLoadSum != null) {
			if (selectCurrentStockLoadSum.getCount() > 0) {
				while (selectCurrentStockLoadSum.moveToNext()) {
					Log.v(TAG, "XXX Display Main Summary");
					String RouteName = selectCurrentStockLoadSum.getString(1);
					String NoOutlet = selectCurrentStockLoadSum.getString(2);
					String RDTarget = selectCurrentStockLoadSum.getString(4);
					String RDRemark1 = selectCurrentStockLoadSum.getString(4);
					etdmitirouteval.setText(RouteName);
					etdmitioutletval.setText(NoOutlet);
					etdmitirdtargetval.setText(RDTarget);
					etdmitineraryremarkval.setText(RDRemark1);

				}
			} else {
				Log.v(TAG, "XXX Display Main Summary");
			}
		}
		selectCurrentStockLoadSum.close();

	}

	private String getCurrentTimeString() {
		// 2013-10-04 00:00:00.000
		Date dateNow = new Date();
		Calendar c = Calendar.getInstance();
		SimpleDateFormat ddMMMyyFormat = new SimpleDateFormat("dd/MM/yyyy");
		String date_to_string = ddMMMyyFormat.format(dateNow);
		String[] separatedTime = date_to_string.split("/");
		// Recreate TxnDate
		selectedCalYear = separatedTime[2]; // year
		selectedCalMonth = separatedTime[1]; // month
		selectedCalDate = separatedTime[0]; // date
		return date_to_string;
	}

	private String getCurrentTimeIdentifire() {
		// 2013-10-04 00:00:00.000
		Date dateNow = new Date();
		Calendar c = Calendar.getInstance();
		SimpleDateFormat ddMMMyyFormat = new SimpleDateFormat("MMyyyy");
		IDENTIFIRE = ddMMMyyFormat.format(dateNow);
		return IDENTIFIRE;
	}

	private String getCurrentMonthName() {
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat month_date = new SimpleDateFormat("MMMMMMMMM");
		month_name = month_date.format(cal.getTime());
		return null;
	}

	private void deviceName() {
		// TODO Auto-generated method stub
		String Model = android.os.Build.MODEL;
		String id = android.os.Build.ID;
		deviceUser = Model + "_" + id;
	}

	// ********Calender View ************
	protected void setNextMonth() {
		if (month.get(GregorianCalendar.MONTH) == month
				.getActualMaximum(GregorianCalendar.MONTH)) {
			month.set((month.get(GregorianCalendar.YEAR) + 1),
					month.getActualMinimum(GregorianCalendar.MONTH), 1);
		} else {
			month.set(GregorianCalendar.MONTH,
					month.get(GregorianCalendar.MONTH) + 1);
		}

	}

	protected void setPreviousMonth() {
		if (month.get(GregorianCalendar.MONTH) == month
				.getActualMinimum(GregorianCalendar.MONTH)) {
			month.set((month.get(GregorianCalendar.YEAR) - 1),
					month.getActualMaximum(GregorianCalendar.MONTH), 1);
		} else {
			month.set(GregorianCalendar.MONTH,
					month.get(GregorianCalendar.MONTH) - 1);
		}

	}

	protected void showToast(String string) {
		Toast.makeText(this, string, Toast.LENGTH_SHORT).show();

	}

	public void refreshCalendar() {
		TextView title = (TextView) findViewById(R.id.title);

		adapter.refreshDays();
		adapter.notifyDataSetChanged();
		handler.post(calendarUpdater); // generate some calendar items

		title.setText(android.text.format.DateFormat.format("MMMM yyyy", month));
	}

	public Runnable calendarUpdater = new Runnable() {

		@Override
		public void run() {
			items.clear();

			// Print dates of the current week
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
			String itemvalue;
			for (int i = 0; i < 7; i++) {
				itemvalue = df.format(itemmonth.getTime());
				itemmonth.add(GregorianCalendar.DATE, 1);
				items.add("2012-09-12");
				items.add("2012-10-07");
				items.add("2012-10-15");
				items.add("2012-10-20");
				items.add("2012-11-30");
				items.add("2012-11-28");
			}

			adapter.setItems(items);
			adapter.notifyDataSetChanged();
		}
	};

	// ********End Calender View ************
	// Handling Dialog Box Functions
	@Override
	protected Dialog onCreateDialog(int id) {

		switch (id) {
		case DIALOG_CANCEL_INVOICE:
			LayoutInflater inflater = LayoutInflater.from(this);
			View dialogview = inflater.inflate(
					R.layout.dm_dialog_cancel_invoice, null);

			AlertDialog.Builder dialogbuilder = new AlertDialog.Builder(this);
			dialogbuilder.setTitle("Cancel Current Itinarary Details...");
			dialogbuilder.setView(dialogview);
			InvoiceHeaderAlert = dialogbuilder.create();
			InvoiceHeaderAlert.setCanceledOnTouchOutside(false);

			break;

		case DIALOG_UNDO_INVOICE:
			LayoutInflater inflateru = LayoutInflater.from(this);
			View dialogviewu = inflateru.inflate(
					R.layout.dm_dialog_undo_invoice, null);

			AlertDialog.Builder dialogbuilderu = new AlertDialog.Builder(this);
			dialogbuilderu.setTitle("Undo Current Itinarary Details...");
			dialogbuilderu.setView(dialogviewu);
			InvoiceHeaderAlert = dialogbuilderu.create();
			InvoiceHeaderAlert.setCanceledOnTouchOutside(false);
			break;

		case DIALOG_PRINT_INVOICE:
			LayoutInflater inflaterp = LayoutInflater.from(this);
			View dialogviewp = inflaterp.inflate(
					R.layout.dm_dialog_save_adjustment, null);

			AlertDialog.Builder dialogbuilderp = new AlertDialog.Builder(this);
			dialogbuilderp.setTitle("Printing Configuration Failure...");
			dialogbuilderp.setView(dialogviewp);
			InvoiceHeaderAlert = dialogbuilderp.create();
			InvoiceHeaderAlert.setCanceledOnTouchOutside(false);
			break;

		case DIALOG_SAVE_INVOICE:
			LayoutInflater inflaters = LayoutInflater.from(this);
			View dialogviews = inflaters.inflate(
					R.layout.dm_dialog_save_adjustment, null);

			AlertDialog.Builder dialogbuilders = new AlertDialog.Builder(this);
			dialogbuilders.setTitle("Itinarary Saved Successfully...");
			dialogbuilders.setView(dialogviews);
			InvoiceHeaderAlert = dialogbuilders.create();
			InvoiceHeaderAlert.setCanceledOnTouchOutside(false);
			break;

		case DIALOG_SELECT_CUSTOMER:
			LayoutInflater inflatercus = LayoutInflater.from(this);
			View dialogviewcus = inflatercus.inflate(
					R.layout.dm_dialog_select_customer, null);

			AlertDialog.Builder dialogbuildercus = new AlertDialog.Builder(this);
			dialogbuildercus.setTitle("Please Select Customer...");
			dialogbuildercus.setView(dialogviewcus);
			InvoiceHeaderAlert = dialogbuildercus.create();
			InvoiceHeaderAlert.setCanceledOnTouchOutside(false);
			break;
		}

		return InvoiceHeaderAlert;
	}

	@Override
	public void onBackPressed() {
		// Do Here what ever you want do on back press;
	}
}